package com.guli.gulimall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.JsonObject;
import com.guli.common.utils.R;
import com.guli.gulimall.product.config.GuliEsConfig;
import com.guli.gulimall.product.dao.*;
import com.guli.gulimall.product.entity.*;
import com.guli.gulimall.product.feign.CouponFeignService;
import com.guli.gulimall.product.service.*;
import com.guli.gulimall.product.to.MemberPriceTo;
import com.guli.gulimall.product.to.SkuFullReductionTo;
import com.guli.gulimall.product.to.SkuLadderTo;
import com.guli.gulimall.product.to.SpuBoundsTo;
import com.guli.gulimall.product.vo.EsSkuVo;
import com.guli.gulimall.product.vo.Images;
import com.guli.gulimall.product.vo.Skus;
import com.guli.gulimall.product.vo.SpuVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;


@Service("spuInfoService")
@SuppressWarnings("all")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpu(SpuVo spuVo) {
        //---------------------pms数据库---------------------
        //1.pms_spu_info spu的基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
         //1.1属性复制
        BeanUtils.copyProperties(spuVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);

        //2.pms_spu_info_desc spu的介绍信息（图片介绍信息）
          //2.1拼接图片地址

         if (!spuVo.getDecript().isEmpty()){
             String url="";
             for (String s : spuVo.getDecript()) {
                 url+=","+s;
             }
             url=url.substring(1);
             SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
             spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
             spuInfoDescEntity.setDecript(url);
             spuInfoDescDao.insert(spuInfoDescEntity);
         }

        //3.pms_spu_images (商品左上角小图介绍)
        if (!spuVo.getImages().isEmpty()){
            List<SpuImagesEntity> collect = spuVo.getImages().stream().map(url -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(url);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            //service才有批量添加
            spuImagesService.saveBatch(collect);

        }
        //4.pms_product_attr_value  spu的规格参数信息
        if (!spuVo.getBaseAttrs().isEmpty()){
            List<ProductAttrValueEntity> collect = spuVo.getBaseAttrs().stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrSort(0);
                productAttrValueEntity.setAttrId(attr.getAttrId());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());
                productAttrValueEntity.setQuickShow(attr.getShowDesc());
                //数据查询属性信息，得到名称和是否要检索
                AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setSearchType(attrEntity.getSearchType());

                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(collect);


        }
        //5.sms_spu_bounds 购物积分表

           //5.1创建一个to对象

        if (spuVo.getBounds()!=null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
            spuBoundsTo.setBuyBounds(spuVo.getBounds().getBuyBounds());
            spuBoundsTo.setGrowBounds(spuVo.getBounds().getGrowBounds());
            R r=couponFeignService.saveBounds(spuBoundsTo);
        }


        if (!spuVo.getSkus().isEmpty()){
            for (Skus skus : spuVo.getSkus()) {
                //6.pms_sku_info sku的基本信息表
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(skus,skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
                  //获取默认tu
                /*if(!sku.getImages().isEmpty()){
                    //jdk1.8
                    String imgUrl = sku.getImages().stream().filter(img -> {
                        return img.getDefaultImg().equals(1);
                    }).findFirst().get().getImgUrl();
                    skuInfoEntity.setSkuDefaultImg(imgUrl);
                }*/



                 if (!skus.getImages().isEmpty()){
                     String imgUrl = skus.getImages().stream().filter(img -> {
                         return img.getDefaultImg()==1;
                     }).findFirst().get().getImgUrl();
                     skuInfoEntity.setSkuDefaultImg(imgUrl);
                 }
                 skuInfoDao.insert(skuInfoEntity);

                //7.pms_sku_images sku的图片信息表
                if (!skus.getImages().isEmpty()){
                    List<SkuImagesEntity> collect = skus.getImages().stream().filter(img -> {
                        return StringUtils.isNotEmpty(img.getImgUrl());
                    }).map(img -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(img, skuImagesEntity);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setImgSort(0);
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(collect);
                }

                //8.pms_sku_sale_attr_value sku的销售属性表
                if (!skus.getAttr().isEmpty()){
                    List<SkuSaleAttrValueEntity> collect = skus.getAttr().stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuSaleAttrValueEntity.setAttrSort(0);
                        //查询属性表得到是否要检索
                        AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());

                        skuSaleAttrValueEntity.setSearchType(attrEntity.getSearchType());
                        return skuSaleAttrValueEntity;


                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(collect);
                }

                //---------------------sms数据库---------------------
                //9.sms_sku_ladder 打折表
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                skuLadderTo.setAddOther(skus.getCountStatus());
                skuLadderTo.setFullCount(skus.getFullCount());
                skuLadderTo.setDiscount(skus.getDiscount());
                R r2= couponFeignService.saveSkuLadder(skuLadderTo);


                //10. sms_sku_full_reduction 满减
                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuFullReductionTo.setAddOther(skus.getPriceStatus());
                skuFullReductionTo.setFullPrice(skus.getFullPrice());
                skuFullReductionTo.setReducePrice(skus.getReducePrice());
                R r3=couponFeignService.saveReduction(skuFullReductionTo);


                //11.sms_member_price  sku的会员价格表
                if (!skus.getMemberPrice().isEmpty()){
                    List<MemberPriceTo> collect = skus.getMemberPrice().stream().map(m -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberPrice(m.getPrice());
                        memberPriceTo.setMemberLevelId(m.getId());
                        memberPriceTo.setMemberLevelName(m.getName());
                        return memberPriceTo;
                    }).collect(Collectors.toList());

                    R r4=couponFeignService.saveMemberPrices(collect);

                }

            }//sku循环结束
        }
    }

    @Override
    public void up(Long spuId) {
        try {
        //查询商品的基本信息
        SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId);
          //1。1规格参数
        QueryWrapper<ProductAttrValueEntity> w2 = new QueryWrapper<>();
        w2.eq("search_type",1);
        w2.eq("spu_id",spuId);
        List<ProductAttrValueEntity> list = productAttrValueService.list(w2);
        List<EsSkuVo.Attr> attrs=null;
        if (!list.isEmpty()){
            attrs = list.stream().map(attr -> {
                EsSkuVo.Attr attrVo = new EsSkuVo.Attr();
                attrVo.setAttrId(attr.getAttrId());
                attrVo.setAttrName(attr.getAttrName());
                attrVo.setAttrValue(attr.getAttrValue());
                return attrVo;
            }).collect(Collectors.toList());
        }

        //所有的sku信息
        QueryWrapper<SkuInfoEntity> w1 = new QueryWrapper<>();
        w1.eq("spu_id",spuId);
        List<SkuInfoEntity> skuList = skuInfoDao.selectList(w1);
        //3.封装数据
        BulkRequest bulkRequest = new BulkRequest("product");
        for (SkuInfoEntity sku : skuList) {
            EsSkuVo esSkuVo = new EsSkuVo();
            esSkuVo.setSkuPrice(sku.getPrice());
            esSkuVo.setSkuImg(sku.getSkuDefaultImg());
            esSkuVo.setSkuTitle(sku.getSkuTitle());
            esSkuVo.setSpuId(spuInfoEntity.getId());
            esSkuVo.setSkuId(sku.getSkuId());
            esSkuVo.setSaleCount(sku.getSaleCount());
            esSkuVo.setHotScore(0L);
            //仓储服务
            esSkuVo.setHasStock(true);
            esSkuVo.setBrandId(spuInfoEntity.getBrandId());
            BrandEntity brandEntity = brandDao.selectById(spuInfoEntity.getBrandId());
            esSkuVo.setBrandName(brandEntity.getName());
            esSkuVo.setBrandImg(brandEntity.getLogo());
            esSkuVo.setCatalogId(spuInfoEntity.getCatalogId());
            CategoryEntity categoryEntity = categoryDao.selectById(spuInfoEntity.getCatalogId());

            esSkuVo.setCatalogName(categoryEntity.getName());
            //属性包含两个
            //3.1通过skuid查销售属性
            QueryWrapper<SkuSaleAttrValueEntity> w3 = new QueryWrapper<>();
            w3.eq("sku_id", sku.getSkuId());
            w3.eq("search_type", 1);
            List<SkuSaleAttrValueEntity> saleList = skuSaleAttrValueService.list(w3);
            if (!saleList.isEmpty()) {
                List<EsSkuVo.Attr> collect = saleList.stream().map(attr -> {
                    EsSkuVo.Attr attrVo = new EsSkuVo.Attr();
                    attrVo.setAttrId(attr.getAttrId());
                    attrVo.setAttrName(attr.getAttrName());
                    attrVo.setAttrValue(attr.getAttrValue());
                    return attrVo;
                }).collect(Collectors.toList());
                collect.addAll(attrs);
                esSkuVo.setAttrs(collect);
            }
            //4.把每个sku添加到es
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(sku.getSkuId().toString());
            String jsonString = JSONObject.toJSONString(esSkuVo);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
            }
            //同步es
            restHighLevelClient.bulk(bulkRequest, GuliEsConfig.COMMON_OPTIONS);
             //修改商品状态
            spuInfoEntity.setPublishStatus(1);
            baseMapper.updateById(spuInfoEntity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
